package lab;

//import lab6_2.Simulation2012.queues.QueueForTransactions;
//import lab6_2.Simulation2012.queues.Store;
import process.Actor;
import process.IWaitCondition;
import process.QueueForTransactions;
import process.Store;
import rnd.Randomable;

public class Kran extends Actor {
	
	private Store  cont;
	private QueueForTransactions gruzovikToKran;
	private Store qSquare;
	private double finish;
	private Randomable rnd;
	private int maxSquare;
	
	public Kran(String name,mainGUI g,Model model){
		setNameForProtocol(name);
		cont= model.getqContainer();
		gruzovikToKran = model.getqGruzovik();
		maxSquare= g.getSizeOfSquare().getInt();
		qSquare = model.getqSquare();
		finish = g.getTimeWork().getDouble();
		rnd = g.getTimeKranRandom();
	}

	@Override
	protected void rule() {
		// TODO Auto-generated method stub
		 IWaitCondition countOfCont = new IWaitCondition(){

			@Override
			public boolean testCondition() {
				// TODO Auto-generated method stub
				return cont.getSize()>0 && qSquare.getSize()<maxSquare;
			}
			
			public String toString(){
				return "konteynerov dolgno but bolee 0 i na ploschadke dolgno but mesto";
			}
		 };
		 
		 	IWaitCondition isEmptyGruzovik = new IWaitCondition() {
				
				@Override
				public boolean testCondition() {
					// TODO Auto-generated method stub
					return gruzovikToKran.size()>0 && !((Gruzovik)gruzovikToKran.peekFirst()).isFull() && qSquare.getSize()>0;
				}
				
				public String toString(){
					return "pystoy gryzovic?";
				}
			};
		 
		 
		 
			do {

				try {
					waitForCondition(countOfCont);
				} catch (Exception e) {
					return;
				}
				while (countOfCont.testCondition()){
					holdForTime(rnd.next());
					qSquare.add(1);
					cont.remove(1);
					getDispatcher().printToProtocol(
							getNameForProtocol() + "taynet yaschik s koroblay");
				}
						
				try {
					waitForCondition(isEmptyGruzovik);
				} catch (Exception e) {
					return;
				}
				while (isEmptyGruzovik.testCondition()) {
				getDispatcher().printToProtocol(
				getNameForProtocol()
								+ " logut ayschik v gryzovic "
								+ ((Gruzovik) (gruzovikToKran.peekFirst())).getNameForProtocol());
				((Gruzovik) (gruzovikToKran.peekFirst())).addPortion();
				qSquare.remove(1);
				holdForTime(rnd.next());
				
				}
			}while (getDispatcher().getCurrentTime() <= finish);


	}

}
